/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 *
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.constant.StringConstant;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.service.ReportCopyRecordService;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.MathUtil;
import com.yixun.qfbao.util.PageUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.PremisesRecommender;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.dto.FollowUpListDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.CommissionStatusEnum;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.FollowUpListService;
import com.yixun.qfbao.xf.service.PremisesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * [文件名称]<br>
 * CustomerPremisesServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 报备相关<br>
 * <br>
 *
 * @author JHSong
 * @version 1.00
 */
@Slf4j
@Service
public class CPServiceImpl implements CPService {

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private CustomerPremisesService customerPremisesService;

    @Autowired
    private CaseMemberService caseMemberService;

    @Autowired
    private PremisesService premisesService;

    @Autowired
    private PartnerInfoService partnerInfoService;

    @Autowired
    private PersonnelService personnelService;

    @Autowired
    private CustomerPremisesMapper customerPremisesMapper;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyRelationService companyRelationService;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private FollowUpListService followUpListService;

    @Autowired
    private RoleResourcesService roleResourcesService;

    @Autowired
    private RoleCaseMemberService roleCaseMemberService;

    @Autowired
    private PremisesRecommenderService premisesRecommenderService;

    @Autowired
    private EstateAdviserService estateAdviserService;
    @Autowired
    private DataCenterService dataCenterService;
    @Autowired
    private ReportCopyRecordService reportCopyRecordService;
    @Autowired
    private com.yixun.qfbao.service.CompanyRelationService companyRelationService2;
    @Autowired
    private CustomerApiService customerApiService;
    @Autowired
    private PremisesPermissionService premisesPermissionService;
    @Autowired
    private DeptPermissionService deptPermissionService;

    /**
     * 案场助手首页统计 待处理报备、待分配报备、待处理申诉 JHSong
     */
    @Override
    public GetAssistantAppIndexResDto getAssistantAppIndex(GetAssistantAppIndexReqDto reqDto) {
        GetAssistantAppIndexResDto resDto = new GetAssistantAppIndexResDto();
        try {
            Map<String, Object> map = supplyRole(reqDto);
            // 判断用户被指定楼盘是否为临时权限(目前只有置业顾问是临时权限)
            PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
            List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
            CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
            List<Long> premisesPermission = premisesPermissionService.getPartnerPremisesPermission(Long.valueOf(reqDto.getUserId()));
            if(CollectionUtils.isEmpty(premisesPermission)) {
            	cusPreDto.setAuthorityPremisesIds(Arrays.asList(-1L));
            }else {
            	cusPreDto.setAuthorityPremisesIds(premisesPermission);
            }
            if(reqDto.getAllPremisesFlag() != null && !reqDto.getAllPremisesFlag()) {
            	if(CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
                	cusPreDto.setPremisesIds(reqDto.getPremisesIds());
                }else {
                	cusPreDto.setPremisesIds(Arrays.asList(-1L));
                }
            }
            List<String> adviserUuids = null;
            if (CollectionUtils.isNotEmpty(estateAdviserList)) {
                adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            }

            List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));

            // 待确认数量: 报备记录为报备待审及未到访
            
            if(StringUtils.isNotBlank(reqDto.getPremisesId())) {
            	cusPreDto.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
            }
            cusPreDto.setAdviserUuids(adviserUuids);
            List<String> customerStatusList = new ArrayList<String>();
            customerStatusList.add(CustomerStatusEnum.normal.getNo());
            
            cusPreDto.setCustomerStatusList(customerStatusList);
//            cusPreDto.setExtendCondition("(t.complaints_number is null or t.complaints_number = 0)");
//            if (map.containsKey("canViewPartnerIds")) {
//                cusPreDto.setCanViewPartnerIds((List) map.get("canViewPartnerIds"));
//            }
            if (map.containsKey("cp")) {
                cusPreDto.setRoleReportWay(map.get("cp").toString());
            }
            cusPreDto.setAgencyDeptIds(agencyDeptIds);
            int auditCount = customerPremisesService.count(cusPreDto);
            
            //到访待审数量
            List<String> notVisistCustomerStatusList = new ArrayList<String>();
            notVisistCustomerStatusList.add(CustomerStatusEnum.not_visited.getNo());
            cusPreDto.setCustomerStatusList(notVisistCustomerStatusList);
            cusPreDto.setExtendCondition(null);
            int visitAuditCount = customerPremisesService.count(cusPreDto);
            
            // 待分配数量: 报备记录为已到访到签约前的数量
            cusPreDto = new CustomerPremisesDto();
            if(CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
            	cusPreDto.setPremisesIds(reqDto.getPremisesIds());
            }else {
            	cusPreDto.setPremisesIds(Arrays.asList(-1L));
            }
            if(CollectionUtils.isEmpty(premisesPermission)) {
            	cusPreDto.setAuthorityPremisesIds(Arrays.asList(-1L));
            }else {
            	cusPreDto.setAuthorityPremisesIds(premisesPermission);
            }
            
            cusPreDto.setAdviserUuids(adviserUuids);
            cusPreDto.setCustomerStatus(CustomerStatusEnum.has_visited.getNo());
//            if (map.containsKey("canViewPartnerIds")) {
//                cusPreDto.setCanViewPartnerIds((List) map.get("canViewPartnerIds"));
//            }
            if (map.containsKey("cp")) {
                cusPreDto.setRoleReportWay(map.get("cp").toString());
            }
            cusPreDto.setAgencyDeptIds(agencyDeptIds);
            int distCount = customerPremisesService.count(cusPreDto);

            // 待处理申诉: 报备状态为未确认,申诉次数为1的记录
            cusPreDto = new CustomerPremisesDto();
            if(CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
            	cusPreDto.setPremisesIds(reqDto.getPremisesIds());
            }else {
            	cusPreDto.setPremisesIds(Arrays.asList(-1L));
            }
            if(CollectionUtils.isEmpty(premisesPermission)) {
            	cusPreDto.setAuthorityPremisesIds(Arrays.asList(-1L));
            }else {
            	cusPreDto.setAuthorityPremisesIds(premisesPermission);
            }
            cusPreDto.setAdviserUuids(adviserUuids);
            cusPreDto.setCustomerStatus(CustomerStatusEnum.normal.getNo());
            // 申诉次数: 1次为有效申诉.
            cusPreDto.setComplaintsNumber(1L);
//            if (map.containsKey("canViewPartnerIds")) {
//                cusPreDto.setCanViewPartnerIds((List) map.get("canViewPartnerIds"));
//            }
            if (map.containsKey("cpAppeal")) {
                cusPreDto.setRoleReportWay(map.get("cpAppeal").toString());
            }
            cusPreDto.setAgencyDeptIds(agencyDeptIds);
            int appealCount = customerPremisesService.count(cusPreDto);

            resDto.setAuditCount(String.valueOf(auditCount));
            resDto.setVisitAuditCount(String.valueOf(visitAuditCount));
            resDto.setDistCount(String.valueOf(distCount));
            resDto.setAppealCount(String.valueOf(appealCount));
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        } catch (Exception ex) {
            log.error("案场助手首页,数据统计错误: {}", ex);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("案场助手首页,数据统计错误: " + ex.getMessage());
        }
        return resDto;
    }

    private Map<String, Object> supplyRole(GetAssistantAppIndexReqDto reqDto) {
        Map<String, Object> map = new HashMap<>();
        List<Long> canViewPartnerIds = Lists.newArrayList();
        //获取角色数据权限
        String userId = reqDto.getUserId();
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(userId));
        Long roleId = partnerInfo.getUserRoleId();
        Map<String, String> dpMap = roleCaseMemberService.getDeptPermissionByRoleId(roleId);
        String dpType = StringUtils.defaultIfBlank(dpMap.get(DPDescEnum.DP_TYPE.getNo()), DeptPermissionEnum.ALL.getNo());
        if (StringUtils.equals(DeptPermissionEnum.NOT.getNo(), dpType)) {
            List<Long> deptIds = roleCaseMemberService.listDeptByRoleId(roleId);
            if (deptIds != null && deptIds.size() > 0) {
                canViewPartnerIds = partnerInfoService.listPartnerInfoIdByDeptIds(deptIds);
            }
            if (canViewPartnerIds != null && canViewPartnerIds.size() != 0) {
                map.put("canViewPartnerIds", canViewPartnerIds);
            }
        }

        //显隐号权限
        if (roleId != null && roleId != 0L && roleId != -1L) {
            //报备的两个权限 menu_0005_0001_0013隐号 menu_0005_0001_0014全号
            List<String> codes = Lists.newArrayList();
            codes.add("menu_0005_0001_0013");
            codes.add("menu_0005_0001_0014");
            List<RoleResources> roleResources = roleResourcesService.listRoleResources(roleId, codes);
            int temp = 0;
            if (roleResources != null && roleResources.size() > 0) {
                if (roleResources.size() > 2) {
                    //这个权限异常
                    temp = 3;
                }
                for (RoleResources roleResource : roleResources) {
                    if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0013")) {
                        temp += 2;
                    } else {
                        temp += 1;
                    }
                }
            }
            map.put("cp", temp);
            codes = Lists.newArrayList();
            codes.add("menu_0005_0002_0003");
            codes.add("menu_0005_0002_0004");
            List<RoleResources> roleResourcesAppeal = roleResourcesService.listRoleResources(roleId, codes);
            int tempAppeal = 0;
            if (roleResourcesAppeal != null && roleResourcesAppeal.size() > 0) {
                if (roleResourcesAppeal.size() > 2) {
                    //这个权限异常
                    tempAppeal = 3;
                }
                for (RoleResources roleResource : roleResourcesAppeal) {
                    if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0002_0003")) {
                        tempAppeal += 2;
                    } else {
                        tempAppeal += 1;
                    }
                }
            }
            map.put("cpAppeal", tempAppeal);
        }
        return map;
    }


    /**
     * 案场助手首页统计 待处理报备、待分配报备、待处理申诉 JHSong
     */
    @Override
    public GetCPStatisticsByPremisesResDto getCPStatisticsByPremises(GetCPStatisticsByPremisesReqDto reqDto) {
        GetCPStatisticsByPremisesResDto resDto = new GetCPStatisticsByPremisesResDto();
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        try {
            List<Integer> reportCountList = new ArrayList<Integer>();
            resDto.setReportCountList(reportCountList);
            List<Long> premisesIds = new ArrayList<Long>(); // 项目id集合
            // 获取用户选择的项目id，如选择‘全部’，则先查询所有项目id
            if (StringUtils.isNotBlank(reqDto.getPremisesId())) {
                premisesIds.add(Long.parseLong(reqDto.getPremisesId()));
            } else {
                if (StringUtils.isBlank(reqDto.getPremisesIds())) {
                    return resDto;
                }
                String[] pids = reqDto.getPremisesIds().split(",");
                for (int i = 0; i < pids.length; i++) {
                    premisesIds.add(Long.parseLong(pids[i]));
                }
            }

            CustomerPremisesDto entity = new CustomerPremisesDto();
            entity.setPremisesIds(premisesIds);
            List<CustomerPremisesDto> cpDtoList = customerPremisesService.selectCustomerByPremises(entity);
            if (null != cpDtoList && cpDtoList.size() > 0) {
                for (CustomerPremisesDto cpDto : cpDtoList) {
                    reportCountList.add(cpDto.getReportCount());
                }
            }
            resDto.setReportCountList(reportCountList);
        } catch (Exception ex) {
            log.error("案场助手首页,客户统计错误: {}", ex);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("巧渠道首页,客户统计错误: " + ex.getMessage());
        }
        return resDto;
    }

    @Override
    public GetAgencyPCIndexResDto getAgencyPcIndex(GetAgencyPCIndexReqDto reqDto)
            throws Exception {
        GetAgencyPCIndexResDto resDto = new GetAgencyPCIndexResDto();
        IndexBasicDto basic = new IndexBasicDto();
        // 查询经纪人数量(当前登录人所属公司的所有经纪人)
        Integer partnerInfos = personnelService.selectPartnerCountByCompanyId(reqDto.getMerchantId());
        basic.setBrokersNumber(partnerInfos == null ? 0 : partnerInfos);
        Long staffId = null;
        // 是否是管理员(0是 1否)
        if (PartnerInfoEnum.ACCOUNT_INDIVIDUAL.getCode().equals(reqDto.getAccountType())) {
            // 非管理员,需添加业务员过滤.不能展示非此业务员驻守的楼盘
            staffId = Long.valueOf(reqDto.getUserId());
        }
        // 成交量：该商户下，所有报备记录中，报备状态为【已结佣】的数量
        Integer volume = customerPremisesMapper.selectByCompanyId(reqDto.getMerchantId(), CommissionStatusEnum.has_commission.getNo(), staffId);

        // 报备数：该商户下，所有已提交的报备记录数量（即不论是何种报备状态）
        Integer reportNumber = customerPremisesMapper.selectByCompanyId(reqDto.getMerchantId(), null, staffId);
        // 已获佣金合计：该商户所有员工【已结佣】佣金之和
        BigDecimal commissionTotol = customerPremisesMapper.sumTotal(reqDto.getMerchantId(), staffId);
        // 成交率：成交量 / 报备数
        if (reportNumber > 0 && volume > 0) {
            basic.setTurnoverRate(new BigDecimal(MathUtil.formatDigits(MathUtil.multiply(MathUtil.divide(volume, reportNumber), 100d))));

        } else {
            basic.setTurnoverRate(new BigDecimal("0.00"));
        }

        basic.setVolume(volume);
        basic.setReportNumber(reportNumber);
        basic.setCommissionTotol(commissionTotol == null ? new BigDecimal("0.00") : commissionTotol);

        Company company = companyService.getCompanyById(reqDto.getMerchantId());
        if (CommisionEnum.COMMISION_STATE_1.getCode().equals(company.getCommissionFlag())) {
            // 将佣金相关的置为0
            basic.setCommissionTotol(new BigDecimal(0));
        }
        // 是否是管理员(0是 1否)
        if (PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(reqDto.getAccountType())) {
            basic.setIsAdmin(true);
        } else {
            basic.setIsAdmin(false);
        }

        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setIndexBasicDto(basic);
        return resDto;
    }

    @Override
    public Integer selectCountByCompanyId(Long companyId, String commissionStatus, long staffId) {
        return customerPremisesMapper.selectByCompanyId(companyId, commissionStatus, staffId);
    }

    @Override
    public BigDecimal getCommissionAmountTotal(Long companyId, Long staffId) {
        return customerPremisesMapper.sumTotal(companyId, staffId);
    }

    /**
     * 导出报备记录
     */
    @Override
    public ExportCPResDto exportCP(ExportCPReqDto reqDto) {
        ExportCPResDto resDto = new ExportCPResDto();
        resDto.setResult(ResultEnum.FAIL.getNo());
        int pageNo = 1;
        int pageSize = 5000;// 导出条数暂时设置成10万条
        try {
            CustomerPremisesDto entity = new CustomerPremisesDto();
            Map<String, Integer> map = PageUtil.getPageInfo(pageNo, pageSize);
            PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
            // 构建当前登录人可查看楼盘权限
            List<Long> authorityPremises = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
            if(CollectionUtils.isEmpty(authorityPremises)){
            	entity.setAuthorityPremisesIds(Arrays.asList(-1L));
            }else{
            	entity.setAuthorityPremisesIds(authorityPremises);
            }
            if (StringUtils.isNotEmpty(reqDto.getPremisesId())) {
                entity.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
            }
            // 机构权限.直接以机构来查询.
            List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
            entity.setAgencyDeptIds(deptPermissionList);
            entity.setAgencyDeptId(reqDto.getAgencyDeptId());
            if (!StringUtils.isEmpty(reqDto.getCustomerStatus())) {
                entity.setCustomerStatus(reqDto.getCustomerStatus());
            }
            if (!StringUtils.isEmpty(reqDto.getConfirmStatus())) {
                entity.setConfirmStatus(reqDto.getConfirmStatus());
            }
            // 增加无效状态处理
            switch (StringUtils.isEmpty(entity.getCustomerStatus()) ? " " : entity.getCustomerStatus()) {
                case "a":
                    entity.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                    entity.setDisableType(DisableTypeEnum.report_invalid.getNo());
                    break;
                case "b":
                    entity.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                    entity.setDisableType(DisableTypeEnum.visit_invalid.getNo());
                    break;
                default:
                    break;
            }
            switch (StringUtils.isEmpty(entity.getConfirmStatus()) ? " " : entity.getConfirmStatus()) {
                case "A":
                    entity.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                    entity.setDisableType(DisableTypeEnum.PAYDEPOSIT_FAILD.getNo());
                    break;
                case "B":
                    entity.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                    entity.setDisableType(DisableTypeEnum.SUBSCRIBE_FAILD.getNo());
                    break;
                case "C":
                    entity.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                    entity.setDisableType(DisableTypeEnum.SIGN_FAILD.getNo());
                    break;
                default:
                    break;
            }

            if (!StringUtils.isEmpty(reqDto.getTimeType())) {
                entity.setTimeType(reqDto.getTimeType());
            }
            if (!StringUtils.isEmpty(reqDto.getCreateTimeBefore())) {
                String before = reqDto.getCreateTimeBefore() + " 00:00:00";
                entity.setCreateTimeBefore(sdf.parse(before));
            }
            if (!StringUtils.isEmpty(reqDto.getCreateTimeAfter())) {
                String after = reqDto.getCreateTimeAfter() + " 23:59:59";
                entity.setCreateTimeAfter(sdf.parse(after));
            }
            // 经纪人
            if (!StringUtils.isEmpty(reqDto.getAgentId())) {
                entity.setStaffId(Long.valueOf(reqDto.getAgentId()));
            }
            // 经纪公司
            if (!StringUtils.isEmpty(reqDto.getCompanyId())) {
                entity.setStaffCompanyId(Long.valueOf(reqDto.getCompanyId()));
            }
            if (StringUtils.isNotEmpty(reqDto.getVisitState())) {
                entity.setVisitState(reqDto.getVisitState());
            }
            if (StringUtils.isNotEmpty(reqDto.getName())) {
                entity.setName(reqDto.getName());
            }
            // 构建机构/门店组别/分销经纪人查询条件
            buildDeptOrPartnerConditionForExport(entity, reqDto, partnerInfo);
            // 推荐人查询
            if (reqDto.getRecommenderId() != null) {
                List<PremisesRecommender> premisesRecommenders = premisesRecommenderService.selectPremisesRecommenderById(reqDto.getRecommenderId());
                List<String> recommenderUuids = premisesRecommenders.stream().map(item -> item.getRecommenderUuid()).collect(Collectors.toList());
                entity.setRecommenderUuids(recommenderUuids);
            }
            if (StringUtils.isNotBlank(reqDto.getReportUserType())) {
                entity.setReportUserType(reqDto.getReportUserType());
            }
            // 不是管理员查询角色权限
            if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(partnerInfo.getAccountType())) {
                List<String> codes = Lists.newArrayList();
                codes.add("menu_0005_0001_0015");
                List<RoleResources> roleResources = roleResourcesService.listRoleResources(partnerInfo.getUserRoleId(), codes);
                if (roleResources != null && roleResources.size() > 0) {
                    for (RoleResources roleResource : roleResources) {
                        if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0015")) {
                            entity.setShowFullNumber(Boolean.FALSE);
                        }
                    }
                }
            }
            List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
            if (CollectionUtils.isNotEmpty(estateAdviserList)) {
                List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
                entity.setAdviserUuids(adviserUuids);
            }
            entity.setOrders(" t.create_time desc");
            entity.setCompanyId(reqDto.getMerchantId());
            Page<CustomerPremisesDto> page = customerPremisesService.getMyPageModel2(entity, map.get("startRow"), map.get("endRow"));
            page.setPageNumber(1);
            page.setTotalPages(com.yixun.qfbao.util.PageUtil.getTotalPage(new Integer(page.getTotal() + ""), pageSize));
            List<CustomerPremisesDto> cpDtoList = page.getRows();

            resDto.setCpDtoList(cpDtoList);
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        } catch (Exception ex) {
            log.error("巧渠道,导出报备记录错误: {}", ex);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("巧渠道,导出报备记录错误: " + ex.getMessage());
        }
        return resDto;
    }

    /**
     * 报备列表
     */
    @Override
    public GetCPPageResDto getCPPage(GetCPPageReqDto reqDto) {
        GetCPPageResDto resDto = new GetCPPageResDto();
        resDto.setResult(ResultEnum.FAIL.getNo());
        if(StringUtils.isBlank(reqDto.getUserId())){
            resDto.setCpDtoPage(null);
            return resDto;
        }
        switch (reqDto.getCustomerStatus() == null ? " " : reqDto.getCustomerStatus()) {
            case "a":
                reqDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                reqDto.setDisableType(DisableTypeEnum.report_invalid.getNo());
                break;
            case "b":
                reqDto.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                reqDto.setDisableType(DisableTypeEnum.visit_invalid.getNo());
                break;
            default:
                break;
        }
        switch (reqDto.getConfirmStatus() == null ? " " : reqDto.getConfirmStatus()) {
            case "A":
                reqDto.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                reqDto.setDisableType(DisableTypeEnum.PAYDEPOSIT_FAILD.getNo());
                break;
            case "B":
                reqDto.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                reqDto.setDisableType(DisableTypeEnum.SUBSCRIBE_FAILD.getNo());
                break;
            case "C":
                reqDto.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                reqDto.setDisableType(DisableTypeEnum.SIGN_FAILD.getNo());
                break;
            default:
                break;
        }
        Page<CustomerPremisesDto> cpDtoPage = null;
        try {
            PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
            suppleRoleCaseMember(reqDto, partnerInfo);
            if (reqDto.getLoginType().equals(SystemIdEnum.DEVELOPERS.getCode())) {
                cpDtoPage = getAssistantCpPage(reqDto, partnerInfo);
            } else if (reqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode()) || reqDto.getLoginType().equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
                cpDtoPage = getAssistantCpPageApp(reqDto, partnerInfo);
            } else if (reqDto.getLoginType().equals(SystemIdEnum.AGENCY_h5.getCode())
                    || reqDto.getLoginType().equals(SystemIdEnum.AGENCY_WEB.getCode()) || reqDto.getLoginType().equals(SystemIdEnum.APP_AGENCY.getCode())
                    || reqDto.getLoginType().equals(SystemIdEnum.WEAPP_AGENCY.getCode())
            ) {
                cpDtoPage = getAgencyCpPage(reqDto);
            }
            // 统计所有报备被复制的次数
            List<CustomerPremisesDto> rows = cpDtoPage.getRows();
            if (CollectionUtils.isNotEmpty(rows)) {
                List<Long> reportIds = rows.stream().map(CustomerPremisesDto::getId).collect(Collectors.toList());
                ReportCopyRecordDto rcrDto = new ReportCopyRecordDto();
                rcrDto.setCopyUser(Long.valueOf(reqDto.getUserId()));
                rcrDto.setReportIds(reportIds);
                List<ReportCopyRecordDto> rcrDtoList = reportCopyRecordService.selectCopyCountByReport(rcrDto);
                Map<Long, Integer> rcrDtoMap = rcrDtoList.stream().collect(Collectors.toMap(ReportCopyRecordDto::getReportId, ReportCopyRecordDto::getCopyCount, (oldValue, newValue) -> newValue));
                rows.forEach(item -> {
                    Integer copyCount = rcrDtoMap.get(item.getId());
                    item.setCopyCount(0);
                    if(Objects.nonNull(copyCount)){
                        item.setCopyCount(copyCount);
                    }
                });
                cpDtoPage.setRows(rows);
            }

            resDto.setCpDtoPage(cpDtoPage);
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        } catch (Exception ex) {
            log.error("获取报备记录异常: {}", ex);
            resDto.setResultMsg("获取报备记录异常: " + ex.getMessage());
        }
        return resDto;
    }

    /**
     * CS 构建可查看的报备经纪人集合
     *
     * @param partnerInfo
     * @return
     */
    private List<Long> bulidCanViewPartnerIds(PartnerInfo partnerInfo) {
        String sysType = null;
        List<Long> canViewPartnerIds = Lists.newArrayList();
        Map<String, String> dpMap = roleCaseMemberService.getDeptPermissionByRoleId(partnerInfo.getUserRoleId());
        String dpType = StringUtils.defaultIfBlank(dpMap.get(DPDescEnum.DP_TYPE.getNo()), DeptPermissionEnum.ALL.getNo());
        //部门权限0不使用1全部2本部3本人
        if (StringUtils.equals(DeptPermissionEnum.NOT.getNo(), dpType)) {
            List<Long> deptIds = roleCaseMemberService.listDeptByRoleId(partnerInfo.getUserRoleId());
            if (deptIds != null && deptIds.size() > 0) {
                canViewPartnerIds = partnerInfoService.listPartnerInfoIdByDeptIds(deptIds);
            }
        } else if (StringUtils.equals(DeptPermissionEnum.ALL.getNo(), dpType) && StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), sysType)) {
        } else if (StringUtils.equals(DeptPermissionEnum.DEPT.getNo(), dpType) && StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), sysType)) {
            List<Department> departments = departmentDao.listDeptByParentId(partnerInfo.getHigherid(), partnerInfo.getDeptId());
            if (CollectionUtils.isNotEmpty(departments)) {
                List<Long> deptIds = departments.stream().map(item -> item.getId()).collect(Collectors.toList());
                List<PartnerInfoDto> infos = partnerInfoService.listPartnerInfoByDeptIds(deptIds);
                List<Long> roleIds = infos.stream().map(item -> item.getUserRoleId()).collect(Collectors.toList());
                List<Long> dpts = roleCaseMemberService.seleteDeptIdsByRoleIds(roleIds);
                canViewPartnerIds = partnerInfoService.listPartnerInfoIdByDeptIds(dpts);
            }
        }
        return canViewPartnerIds;
    }

    private void suppleRoleCaseMember(GetCPPageReqDto getCPPageReqDto, PartnerInfo partnerInfo) {
        //只有这两个系统再去加数据权限
        if (StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), getCPPageReqDto.getLoginType()) ||
                StringUtils.equals(SystemIdEnum.ASSISTANT.getCode(), getCPPageReqDto.getLoginType())) {
            if (partnerInfo != null) {
                Long roleId = partnerInfo.getUserRoleId();
                //没角色 游客
                if (roleId != null && roleId != 0L && roleId != -1L) {
                    //报备的两个权限 menu_0005_0001_0013隐号 menu_0005_0001_0014全号
                    // 经纪人号码隐藏: menu_0005_0001_0020 menu_0008_0007 存在即隐藏
                    List<String> codes = Lists.newArrayList();
                    codes.add("menu_0005_0001_0013");
                    codes.add("menu_0005_0001_0014");
                    codes.add("menu_0005_0001_0015");
                    codes.add("menu_0008_0006");
                    codes.add("menu_0005_0001_0020");
                    codes.add("menu_0008_0007");
                    List<RoleResources> roleResources = roleResourcesService.listRoleResources(roleId, codes);
                    int temp = 0;
                    boolean show = true;
                    boolean hideAgentPhone = false;
                    if (roleResources != null && roleResources.size() > 0) {
                        if (roleResources.size() > 4) {
                            //这个权限异常
                            temp = 3;
                        }
                        for (RoleResources roleResource : roleResources) {
                            if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0013")) {
                                temp += 2;
                            } else {
                                temp += 1;
                            }
                            if (getCPPageReqDto.getLoginType().equals(SystemIdEnum.DEVELOPERS.getCode())) {
                                if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0015")) {
                                    show = false;
                                }
                                if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0020")) {
                                    hideAgentPhone = true;
                                }
                            } else if (getCPPageReqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode()) ||
                                    getCPPageReqDto.getLoginType().equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
                                if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0008_0006")) {
                                    show = false;
                                }
                                if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0008_0007")) {
                                    hideAgentPhone = true;
                                }
                            }
                        }
                    }
                    // 超级管理不受权限控制
                    if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(partnerInfo.getAccountType())) {
                        getCPPageReqDto.setShowFullNumber(show);
                        getCPPageReqDto.setHideAgentPhone(hideAgentPhone);
                    }

                    getCPPageReqDto.setRoleReportWay(String.valueOf(temp));
                    // setCanViewPartnerIds 权限使用 deptPermissionService.getPartnerDeptPermission 代替
                    //getCPPageReqDto.setCanViewPartnerIds(bulidCanViewPartnerIds(partnerInfo));
                    //getCPPageReqDto = (GetCPPageReqDto)getCanViewPartnerIds(roleId, partnerInfo,getCPPageReqDto);
                }
            }
        }
    }

    void getAdviserCustomerPremises(GetCPPageReqDto getCPPageReqDto, PartnerInfo partnerInfo) {

    }

    private void suppleRoleCaseMember(GetCPAppealPageReqDto getCPAppealPageReqDto) {
        //只有这两个系统再去加数据权限
        if (StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), getCPAppealPageReqDto.getLoginType()) ||
                StringUtils.equals(SystemIdEnum.ASSISTANT.getCode(), getCPAppealPageReqDto.getLoginType())) {
            String userId = getCPAppealPageReqDto.getUserId();
            PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(userId));
            if (partnerInfo != null) {
                Long roleId = partnerInfo.getUserRoleId();
                //没角色 游客
                if (roleId != null && roleId != 0L && roleId != -1L) {
                    //报备的两个权限 menu_0005_0002_0003隐号 menu_0005_0002_0004全号
                    List<String> codes = Lists.newArrayList();
                    codes.add("menu_0005_0002_0003");
                    codes.add("menu_0005_0002_0004");
                    codes.add("menu_0005_0001_0020");
                    codes.add("menu_0008_0007");

                    List<RoleResources> roleResources = roleResourcesService.listRoleResources(roleId, codes);
                    int temp = 0;
                    boolean hideAgentPhone = false;
                    if (roleResources != null && roleResources.size() > 0) {
                        if (roleResources.size() > 2) {
                            //这个权限异常
                            temp = 3;
                        }
                        for (RoleResources roleResource : roleResources) {
                            if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0002_0003")) {
                                temp += 2;
                            } else {
                                temp += 1;
                            }

                            if (getCPAppealPageReqDto.getLoginType().equals(SystemIdEnum.DEVELOPERS.getCode())) {
                                if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0005_0001_0020")) {
                                    hideAgentPhone = true;
                                }
                            } else if (getCPAppealPageReqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode()) ||
                                    getCPAppealPageReqDto.getLoginType().equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
                                if (StringUtils.equals(roleResource.getResourcesCode(), "menu_0008_0007")) {
                                    hideAgentPhone = true;
                                }
                            }
                        }
                    }

                    if (!PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(partnerInfo.getAccountType())) {
                        getCPAppealPageReqDto.setHideAgentPhone(hideAgentPhone);
                    }

                    getCPAppealPageReqDto.setRoleReportWay(String.valueOf(temp));
                    //getCPAppealPageReqDto = (GetCPAppealPageReqDto) getCanViewPartnerIds(roleId, partnerInfo, getCPAppealPageReqDto);

                }
            }
        }
    }

    private Object getCanViewPartnerIds(Long roleId, PartnerInfo partnerInfo, Object reqDto) {
        List<Long> canViewPartnerIds = Lists.newArrayList();
        List<Long> premisesIds = Lists.newArrayList();
        GetCPAppealPageReqDto getCPAppealPageReqDto = null;
        GetCPPageReqDto getCPPageReqDto = null;
        String sysType = null;
        if (reqDto instanceof GetCPAppealPageReqDto) {
            getCPAppealPageReqDto = (GetCPAppealPageReqDto) reqDto;
            sysType = getCPAppealPageReqDto.getLoginType();
        } else {
            getCPPageReqDto = (GetCPPageReqDto) reqDto;
            sysType = getCPPageReqDto.getLoginType();
        }


        //报备数据权限 没有查到 是ALL权限
        Map<String, String> dpMap = roleCaseMemberService.getDeptPermissionByRoleId(roleId);
        String dpType = StringUtils.defaultIfBlank(dpMap.get(DPDescEnum.DP_TYPE.getNo()), DeptPermissionEnum.ALL.getNo());
        //部门权限0不使用1全部2本部3本人
        if (StringUtils.equals(DeptPermissionEnum.NOT.getNo(), dpType)) {
            List<Long> deptIds = roleCaseMemberService.listDeptByRoleId(roleId);
            if (deptIds != null && deptIds.size() > 0) {
                canViewPartnerIds = partnerInfoService.listPartnerInfoIdByDeptIds(deptIds);
            }
        } else if (StringUtils.equals(DeptPermissionEnum.ALL.getNo(), dpType) && StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), sysType)) {
        } else if (StringUtils.equals(DeptPermissionEnum.DEPT.getNo(), dpType) && StringUtils.equals(SystemIdEnum.DEVELOPERS.getCode(), sysType)) {
            //向下所有部门
            List<Department> departments = departmentDao.listDeptByParentId(partnerInfo.getHigherid(), partnerInfo.getDeptId());
            if (departments != null && departments.size() > 0) {
                List<Long> deptIds = Lists.newArrayList();
                for (Department department : departments) {
                    deptIds.add(department.getId());
                }
                //本部门所有的员工的角色
                List<PartnerInfoDto> infos = partnerInfoService.listPartnerInfoByDeptIds(deptIds);
                if (infos != null && infos.size() > 0) {
                    List<Long> roleIds = Lists.newArrayList();
                    Set<Long> tempSet = Sets.newHashSet();
                    for (PartnerInfoDto info : infos) {
                        if (info.getUserRoleId() != null) {
                            tempSet.add(info.getId());
                        }
                    }
                    CaseMemberDto caseMemberDto = new CaseMemberDto();
                    caseMemberDto.setCompanyId(partnerInfo.getHigherid());
                    caseMemberDto.setPartnerIds(tempSet);
                    if (getCPAppealPageReqDto != null && getCPAppealPageReqDto.getName() != null) {
                        caseMemberDto.setPremisesName(getCPAppealPageReqDto.getName());
                    } else if (getCPPageReqDto != null && getCPPageReqDto.getName() != null) {
                        caseMemberDto.setPremisesName(getCPPageReqDto.getName());
                    }
                    List<CaseMemberDto> caseMemberList = caseMemberService.selectListForDept(caseMemberDto);
                    if (caseMemberList == null || caseMemberList.size() == 0) {
                        throw new TServerException("未查询到相应楼盘");
                    }

                    for (CaseMemberDto c : caseMemberList) {
                        premisesIds.add(c.getPremisesId());
                    }

                }
            }
        }
        if (getCPAppealPageReqDto != null) {
            getCPAppealPageReqDto.setDeptPermission(dpType);
            if (canViewPartnerIds != null && canViewPartnerIds.size() != 0) {
                getCPAppealPageReqDto.setCanViewPartnerIds(canViewPartnerIds);
            }
            if (premisesIds != null && premisesIds.size() != 0) {
                getCPAppealPageReqDto.setCanViewPremisesIds(premisesIds);
            }

        } else if (getCPPageReqDto != null) {
            getCPPageReqDto.setDeptPermission(dpType);
            if (canViewPartnerIds != null && canViewPartnerIds.size() != 0) {
                getCPPageReqDto.setCanViewPartnerIds(canViewPartnerIds);
            }
            if (premisesIds != null && premisesIds.size() != 0) {
                getCPPageReqDto.setCanViewPremisesIds(premisesIds);
            }

        }
        return reqDto;

    }

    private Page<CustomerPremisesDto> getAssistantCpPageApp(GetCPPageReqDto reqDto, PartnerInfo partnerInfo) {
        String customerStatus = reqDto.getCustomerStatus();
        String confirmStatus = reqDto.getConfirmStatus();
        String statusArr[] = customerStatus.split("[,]");
        List<String> statusList = new ArrayList<String>();
        CustomerPremisesDto cusPreDto = new CustomerPremisesDto();
        if(StringUtils.isNotBlank(reqDto.getPremisesId())) {
        	cusPreDto.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
        }
        // 判断用户被指定楼盘是否为临时权限(目前只有置业顾问是临时权限)
        List<Long> premisesPermission = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
        if(CollectionUtils.isEmpty(premisesPermission)) {
        	cusPreDto.setAuthorityPremisesIds(Arrays.asList(-1L));
        }else {
        	cusPreDto.setAuthorityPremisesIds(premisesPermission);
        }
        if(CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
        	cusPreDto.setPremisesIds(reqDto.getPremisesIds());
        }else {
        	cusPreDto.setPremisesIds(Arrays.asList(-1L));
        }
        
        for (int ii = 0; ii < statusArr.length; ii++) {
            if (StringUtils.isNotEmpty(statusArr[ii])) {
                statusList.add(statusArr[ii]);
            }
        }
        if (statusList.size() > 0) {
            cusPreDto.setCustomerStatusList(statusList);
        }
        if (StringUtils.isNotBlank(confirmStatus)) {
            cusPreDto.setConfirmStatus(confirmStatus);
        }
        cusPreDto.setSearchContent(reqDto.getName());
        /**
         * 2017-11-9 sangtao 注释说明 在代报备时 维护的partner_id为 案场代报备人，有可能不是案场负责人，为什么判断为空，已经搞不清楚了
         * if(CustomerStatusEnum.has_visited.getNo().equals(customerStatus)){ cusPreDto.setExtendCondition(
         * "partner_id is null and confirm_status!=3"); }
         */
        cusPreDto.setOrders("create_time desc");
        if (StringUtils.isNotBlank(reqDto.getRoleReportWay())) {
            cusPreDto.setRoleReportWay(reqDto.getRoleReportWay());
        }
        if (reqDto.getCanViewPartnerIds() != null && reqDto.getCanViewPartnerIds().size() > 0) {
            cusPreDto.setCanViewPartnerIds(reqDto.getCanViewPartnerIds());
        }
        if (reqDto.getShowFullNumber() != null && Boolean.FALSE.equals(reqDto.getShowFullNumber())) {
            cusPreDto.setShowFullNumber(Boolean.FALSE);
        }
        
    	List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            cusPreDto.setAdviserUuids(adviserUuids);
        }

        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
        cusPreDto.setAgencyDeptIds(deptPermissionList);

        Page<CustomerPremises> cusPrePage = customerPremisesService.getPageModel(cusPreDto,
                com.yixun.common.page.PageUtil.begin(reqDto.getPageNo(), reqDto.getPageSize()),
                reqDto.getPageSize());
        Page<CustomerPremisesDto> customerPremisesDtoPage = new Page<>();
        List<CustomerPremisesDto> dtoList = new ArrayList<>();
        List<CustomerPremises> rows = cusPrePage.getRows();
        List<Long> premisesIds = rows.stream().map(CustomerPremises::getPremisesId).collect(Collectors.toList());
        premisesIds = premisesIds.stream().distinct().collect(Collectors.toList());
        PremisesDto preDto = new PremisesDto();
        preDto.setName(reqDto.getName());
        preDto.setPremisesIds(premisesIds);
        List<Premises> premisesList = premisesService.selectIdListByDto(preDto);
        Map<Long, String> completeNodeMap = premisesList.stream().collect(Collectors.toMap(Premises::getId, item -> StringUtils.defaultIfBlank(item.getCompleteNode(), StringUtils.EMPTY), (oldData, newData) -> newData));
        for (CustomerPremises customerPremises : rows) {
            Map<String, String> map = customerPremisesService.getCusStatus(customerPremises);
            customerPremises.setCurrentStatus(map.get("currentStatus"));
            CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
            BeanUtils.copyProperties(customerPremises, customerPremisesDto);
            customerPremisesDto.setCompleteNode(completeNodeMap.get(customerPremises.getPremisesId()));
            if(Objects.nonNull(customerPremises.getHopeVisitTime())){
                customerPremisesDto.setFormatHopeVisitTime(DateUtils.DateToString(customerPremises.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
            }
            if(Objects.nonNull(reqDto.getHideAgentPhone()) && Boolean.TRUE.equals(reqDto.getHideAgentPhone())){
                customerPremisesDto.setStaffPhone(ReportWayEnum.convertMobileByReportWay(customerPremisesDto.getStaffPhone(), ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo()));
            }
            dtoList.add(customerPremisesDto);
        }
        customerPremisesDtoPage.setRows(dtoList);
        customerPremisesDtoPage.setPageNumber(reqDto.getPageNo());
        // 总条数/pageSize 向上取整
        int totalPages = (int) Math.ceil(new Double(cusPrePage.getTotal()) / reqDto.getPageSize().doubleValue());
        customerPremisesDtoPage.setTotalPages(totalPages);
        customerPremisesDtoPage.setPageSize(reqDto.getPageSize());
        return customerPremisesDtoPage;
    }

    private Page<CustomerPremisesDto> getAgencyCpPage(GetCPPageReqDto reqDto)
            throws ParseException {
        CustomerPremisesDto entity = new CustomerPremisesDto();
        if (StringUtils.isNotBlank(reqDto.getSearchContent())) {
            entity.setSearchContent(reqDto.getSearchContent());
        }
        if (StringUtils.isNotBlank(reqDto.getConfirmStatus())) {
            entity.setConfirmStatus(reqDto.getConfirmStatus());
        }
        if (StringUtils.isNotBlank(reqDto.getDisableType())) {
            entity.setDisableType(reqDto.getDisableType());
        }
        if (StringUtils.isNotBlank(reqDto.getPremisesName())) {
            entity.setPremisesName(reqDto.getPremisesName());
        }

        if (StringUtils.isNotBlank(reqDto.getCustomerStatus())) {
            entity.setCustomerStatus(reqDto.getCustomerStatus());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beforeDate = reqDto.getCreateTimeBefore();
        if (StringUtils.isNotBlank(beforeDate)) {
            entity.setCreateTimeBefore(sdf.parse(beforeDate + " 00:00:00"));
        }
        String afertDate = reqDto.getCreateTimeAfter();
        if (StringUtils.isNotBlank(afertDate)) {
            entity.setCreateTimeAfter(sdf.parse(afertDate + " 23:59:59"));
        }
        if (StringUtils.isNotBlank(reqDto.getStoreOrGroup())) {
            entity.setStoreOrGroup(reqDto.getStoreOrGroup());
        }

        // 管理员逻辑
        if ("0".equals(reqDto.getAccountType())) {
            entity.setStaffId(null);
            entity.setStaffCompanyId(reqDto.getMerchantId());
        }else{
            // 用户角色权限
            AgencyPartnerPermission app = deptPermissionService.getAgencyPartnerPermission(Long.parseLong(reqDto.getUserId()));
            log.info("getAgencyCpPage agency partner: {}, permission is: {}", reqDto.getUserId(), JSONObject.toJSON(app));
            if(Objects.isNull(app) || DeptPermissionEnum.MYSELF.getNo().equals(app.getDeptPermission())){
                // 未配置权限或本人权限,以当前用户查询报备记录
                entity.setStaffId(Long.parseLong(reqDto.getUserId()));
            }else if(DeptPermissionEnum.DEPT.getNo().equals(app.getDeptPermission())){
                // 本部,获取用户及其子部门相关所有部门报备数据
                entity.setAgencyDeptIds(app.getPermissionIds());
            }else if(DeptPermissionEnum.ALL.getNo().equals(app.getDeptPermission())){
                // 全部,啥也不管.和管理员一样,直接查公司数据
                entity.setStaffId(null);
                entity.setStaffCompanyId(reqDto.getMerchantId());
            }
        }

        entity.setOrders("t.create_time desc");
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        Page<CustomerPremisesDto> pageList =
                customerPremisesService.getMyPageModel(entity, com.yixun.common.page.PageUtil.begin(pageNo, pageSize), pageSize);
        List<CustomerPremisesDto> rows = pageList.getRows();
        boolean commissionFlag = companyService.getCommissionFlag(reqDto.getMerchantId());
        if (!commissionFlag) {
            // 将与佣金相关的设置为0
            for (CustomerPremises cus : rows) {
                cus.setCommissionAmount("0");
                cus.setReward(new BigDecimal(0));
                cus.setCommissionIsShow("1");
            }
        } else {
            for (CustomerPremises cus : rows) {
                cus.setCommissionIsShow("0");
            }
        }
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 修改列表中的报备时间
        for (CustomerPremisesDto cus : rows) {
            if (cus.getHopeVisitTime() != null) {
                cus.setFormateUpdateTime(sdf2.format(cus.getHopeVisitTime()));// 设置期望带看时间
            }
        }
        return pageList;
    }

    private Page<CustomerPremisesDto> getAssistantCpPage(GetCPPageReqDto reqDto, PartnerInfo partnerInfo)
            throws ParseException {
        CustomerPremisesDto entity = new CustomerPremisesDto();
        Map<String, Integer> map = PageUtil.getPageInfo(reqDto.getPageNo(), reqDto.getPageSize());
        // 构建当前登录人可查看楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
        if(CollectionUtils.isEmpty(premisesIds)){
        	entity.setAuthorityPremisesIds(Arrays.asList(-1L));
        }else{
        	entity.setAuthorityPremisesIds(premisesIds);
        }
        
        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
        entity.setAgencyDeptIds(deptPermissionList);
        entity.setAgencyDeptId(reqDto.getAgencyDeptId());
        // 判断是否指定楼盘检索
        if (StringUtils.isNotBlank(reqDto.getPremisesId())) {
            entity.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
        } else {
            entity.setPremisesId(null);
            // 渠道经理所属经纪人
            List<List<Long>> staffIds = dataCenterService.getStaffIdsByPrincipal(Long.valueOf(reqDto.getUserId()));
            if (CollectionUtils.isNotEmpty(staffIds)) {
                entity.setPrincipalStaffIds(staffIds);
            }
        }
        if (!StringUtils.isEmpty(reqDto.getCustomerStatus())) {
            entity.setCustomerStatus(reqDto.getCustomerStatus());
        }
        if (!StringUtils.isEmpty(reqDto.getConfirmStatus())) {
            entity.setConfirmStatus(reqDto.getConfirmStatus());
        }
        //失败类型
        if (!StringUtils.isEmpty(reqDto.getDisableType())) {
            entity.setDisableType(reqDto.getDisableType());
        }

        if (!StringUtils.isEmpty(reqDto.getTimeType())) {
            entity.setTimeType(reqDto.getTimeType());
        }
        if (!StringUtils.isEmpty(reqDto.getCreateTimeBefore())) {
            String before = reqDto.getCreateTimeBefore() + " 00:00:00";
            entity.setCreateTimeBefore(sdf.parse(before));
        }
        if (!StringUtils.isEmpty(reqDto.getCreateTimeAfter())) {
            String after = reqDto.getCreateTimeAfter() + " 23:59:59";
            entity.setCreateTimeAfter(sdf.parse(after));
        }
        if (StringUtils.isNotBlank(reqDto.getReportUserType())) {
            entity.setReportUserType(reqDto.getReportUserType());
        }
        if (StringUtils.isNotEmpty(reqDto.getVisitState())) {
            entity.setVisitState(reqDto.getVisitState());
        }
        // 构建机构/门店组别/分销经纪人查询条件
        buildDeptOrPartnerCondition(entity, reqDto, partnerInfo);
        // 推荐人查询
        if (reqDto.getRecommenderId() != null) {
            List<PremisesRecommender> premisesRecommenders = premisesRecommenderService.selectPremisesRecommenderById(reqDto.getRecommenderId());
            List<String> recommenderUuids = premisesRecommenders.stream().map(item -> item.getRecommenderUuid()).collect(Collectors.toList());
            entity.setRecommenderUuids(recommenderUuids);
        }
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            entity.setAdviserUuids(adviserUuids);
        }
        entity.setCompanyId(partnerInfo.getHigherid());
//        entity.setSql(" and (process_status = 2 or process_status is null)");
        entity.setOrders(" t.create_time desc");
        if (StringUtils.isNotBlank(reqDto.getRoleReportWay())) {
            entity.setRoleReportWay(reqDto.getRoleReportWay());
        }
        if (reqDto.getCanViewPartnerIds() != null && reqDto.getCanViewPartnerIds().size() > 0) {
            entity.setCanViewPartnerIds(reqDto.getCanViewPartnerIds());
        }
        if (StringUtils.isNotEmpty(reqDto.getName())) {
            entity.setName(reqDto.getName());
        }
        if (reqDto.getShowFullNumber() != null && Boolean.FALSE.equals(reqDto.getShowFullNumber())) {
            entity.setShowFullNumber(Boolean.FALSE);
        }
        entity.setHideAgentPhone(reqDto.getHideAgentPhone());
        if (StringUtils.isNotBlank(reqDto.getMortgageStatus())) {
            entity.setMortgageStatus(reqDto.getMortgageStatus());
        }
        if (StringUtils.isNotBlank(reqDto.getPayFinish())) {
            entity.setPayFinish(reqDto.getPayFinish());
        }
        log.info("getMyPageModel2 userId: {}, params: {}", reqDto.getUserId(), JSONObject.toJSONString(entity));
        Page<CustomerPremisesDto> cpDtoPage = customerPremisesService.getMyPageModel2(entity, map.get("startRow"), map.get("endRow"));
        cpDtoPage.setPageNumber(reqDto.getPageNo());
        cpDtoPage.setTotalPages(com.yixun.qfbao.util.PageUtil.getTotalPage(new Integer(cpDtoPage.getTotal() + ""), reqDto.getPageSize()));
        cpDtoPage.setPageSize(reqDto.getPageSize());
        return cpDtoPage;
    }

    private List<Long> listDepartmentByParentId(Long deptId) {
        List<Long> list = new ArrayList<>();
        DepartmentDto department = new DepartmentDto();
        department.setParentId(deptId);
        List<Department> departmentList = departmentDao.selectListByDto(department);
        list.add(deptId);
        if (departmentList != null && departmentList.size() > 0) {
            for (Department dept : departmentList) {
                list.addAll(listDepartmentByParentId(dept.getId()));
            }
        }
        return list;
    }

    /**
     * 构建机构/门店组别/分销经纪人查询条件
     *
     * @param entity
     * @param reqDto
     * @param partnerInfo
     */
    private void buildDeptOrPartnerCondition(CustomerPremisesDto entity, GetCPPageReqDto reqDto, PartnerInfo partnerInfo) {
        if (StringUtils.isNotEmpty(reqDto.getAgentId())) {
            entity.setStaffId(Long.valueOf(reqDto.getAgentId()));
            return;
        }
        if (reqDto.getStoreOrGroupId() != null) {
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setId(reqDto.getStoreOrGroupId());
            if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo())) {
                CompanyRelationDto companyRelationDto = new CompanyRelationDto();
                companyRelationDto.setDevCompany(partnerInfo.getHigherid());
                List<CompanyRelation> crList = companyRelationService.selectListByDto(companyRelationDto);
                if (crList != null && crList.size() > 0) {
                    List<Long> agenceIdList = crList.stream().map(CompanyRelation::getAgentCompany).collect(Collectors.toList());
                    departmentDto.setMerchantIds(StringUtils.join(agenceIdList, ","));
                }
            }
            List<Department> deptList = departmentDao.selectListByDto(departmentDto);
            if (null != deptList && deptList.size() > 0) {
                List<Long> deptIds = deptList.stream().map(Department::getId).collect(Collectors.toList());
                List<Long> deptIdsTemp = new ArrayList<>();
                for (Long deptId : deptIds) {
                    deptIdsTemp.addAll(listDepartmentByParentId(deptId));
                }
                if (deptIdsTemp != null && deptIdsTemp.size() > 0) deptIds.addAll(deptIdsTemp);
                PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
                partnerInfoDto.setDeptIds(deptIds);
                List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(partnerInfoDto);
                if (null != partnerInfoList && partnerInfoList.size() > 0) {
                    List<Long> partnerIds = partnerInfoList.stream().map(PartnerInfo::getId).collect(Collectors.toList());
                    entity.setPartnerIds(partnerIds);
                }
            }
            return;
        }
        if (!StringUtils.isEmpty(reqDto.getCompanyId())) {
            entity.setStaffCompanyId(Long.valueOf(reqDto.getCompanyId()));
        }
    }

    /**
     * 构建机构/门店组别/分销经纪人查询条件
     *
     * @param entity
     * @param reqDto
     * @param partnerInfo
     */
    private void buildDeptOrPartnerConditionForExport(CustomerPremisesDto entity, ExportCPReqDto reqDto, PartnerInfo partnerInfo) {
        if (StringUtils.isNotEmpty(reqDto.getAgentId())) {
            entity.setStaffId(Long.valueOf(reqDto.getAgentId()));
            return;
        }
        if (reqDto.getStoreOrGroupId() != null) {
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setId(reqDto.getStoreOrGroupId());
            if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo())) {
                CompanyRelationDto companyRelationDto = new CompanyRelationDto();
                companyRelationDto.setDevCompany(partnerInfo.getHigherid());
                List<CompanyRelation> crList = companyRelationService.selectListByDto(companyRelationDto);
                if (crList != null && crList.size() > 0) {
                    List<Long> agenceIdList = crList.stream().map(CompanyRelation::getAgentCompany).collect(Collectors.toList());
                    departmentDto.setMerchantIds(StringUtils.join(agenceIdList, ","));
                }
            }
            List<Department> deptList = departmentDao.selectListByDto(departmentDto);
            if (null != deptList && deptList.size() > 0) {
                List<Long> deptIds = deptList.stream().map(Department::getId).collect(Collectors.toList());
                List<Long> deptIdsTemp = new ArrayList<>();
                for (Long deptId : deptIds) {
                    deptIdsTemp.addAll(listDepartmentByParentId(deptId));
                }
                if (deptIdsTemp != null && deptIdsTemp.size() > 0) deptIds.addAll(deptIdsTemp);
                PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
                partnerInfoDto.setDeptIds(deptIds);
                List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(partnerInfoDto);
                if (null != partnerInfoList && partnerInfoList.size() > 0) {
                    List<Long> partnerIds = partnerInfoList.stream().map(PartnerInfo::getId).collect(Collectors.toList());
                    entity.setPartnerIds(partnerIds);
                }
            }
            return;
        }
        if (!StringUtils.isEmpty(reqDto.getCompanyId())) {
            entity.setStaffCompanyId(Long.valueOf(reqDto.getCompanyId()));
        }
    }

    /**
     * 构建当前登录人员楼盘检索条件
     *
     * @param entity
     * @param reqDto
     * @param partnerInfo
     */
    private void buildPremisesCondition(CustomerPremisesDto entity, GetCPPageReqDto reqDto, PartnerInfo partnerInfo) {
        List<CaseMember> list = new ArrayList<>();
        if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo()) || DeptPermissionEnum.ALL.getNo().equals(reqDto.getDeptPermission())) {
            // 管理员: 获取开发商所有楼盘
            PremisesDto pDto = new PremisesDto();
            pDto.setCompanyId(partnerInfo.getHigherid());
            pDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
            List<Premises> pl = premisesService.selectIdListByDto(pDto);
            for (Premises pr : pl) {
                CaseMember cm = new CaseMember();
                cm.setPremisesId(pr.getId());
                cm.setPremisesName(pr.getName());
                list.add(cm);
            }
        } else {
            // 个人驻守ID
            CaseMemberDto caseMemberDto = new CaseMemberDto();
            caseMemberDto.setPartnerId(partnerInfo.getId());
            caseMemberDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
            caseMemberDto.setCompanyId(partnerInfo.getHigherid());
            list = caseMemberService.selectListByDto(caseMemberDto);
        }
        //当前登录人是否为楼盘项目总监或项目经理
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setMobileTemp(partnerInfo.getPhone());
        premisesDto.setCompanyId(partnerInfo.getHigherid());
        List<Premises> premisesList = premisesService.selectIdListByMobileTemp(premisesDto);
        if (premisesList != null && premisesList.size() > 0) {
            for (Premises premises : premisesList) {
                CaseMember cm = new CaseMember();
                cm.setPremisesId(premises.getId());
                cm.setPremisesName(premises.getName());
                list.add(cm);
            }
        }

        // 置业顾问关联的楼盘.置业顾问关联楼盘,不做为条件查询
		/*
		List<EstateAdviser> adviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
		if(CollectionUtils.isNotEmpty(adviserList)){
			List<Long> premisesIds = adviserList.stream().map(EstateAdviser::getPremisesId).collect(Collectors.toList());
			premisesDto = new PremisesDto();
			premisesDto.setPremisesIds(premisesIds);
			premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			List<Premises> adviserPremisesList = premisesService.selectIdListByDto(premisesDto);
			if(CollectionUtils.isNotEmpty(adviserPremisesList)) {
				for (Premises premises : adviserPremisesList) {
					CaseMember cm = new CaseMember();
					cm.setPremisesId(premises.getId());
					cm.setPremisesName(premises.getName());
					list.add(cm);
				}
			}
		}
		*/

        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> pId = new ArrayList<Long>();
            for (CaseMember cm : list) {
                pId.add(cm.getPremisesId());
            }
            List<Long> premisesIds = new ArrayList<Long>();
            if (!StringUtils.isEmpty(reqDto.getName())) {
                PremisesDto preDto = new PremisesDto();
                preDto.setName(reqDto.getName());

                if (reqDto.getCanViewPremisesIds() != null && reqDto.getCanViewPremisesIds().size() != 0) {
                    /**
                     * 添加数据权限中获取的楼盘id
                     */
                    preDto.setPremisesIds(reqDto.getCanViewPremisesIds());
                } else {
                    preDto.setPremisesIds(pId);
                }
                List<Premises> preList = premisesService.selectIdListByDto(preDto);
                if (preList != null && preList.size() > 0) {
                    for (Premises cmEntity : preList) {
                        premisesIds.add(cmEntity.getId());
                    }
                } else {
                    entity.setName(reqDto.getName());
                    if (CollectionUtils.isNotEmpty(pId)) {
                        premisesIds.addAll(pId);
                    } else {
                        if (null != reqDto.getCanViewPremisesIds() && reqDto.getCanViewPremisesIds().size() > 0) {
                            premisesIds.addAll(reqDto.getCanViewPremisesIds());
                        }
                    }
                }
            } else {
                if (reqDto.getCanViewPremisesIds() != null && reqDto.getCanViewPremisesIds().size() != 0) {
                    /**
                     * 添加数据权限中获取的楼盘id
                     */
                    premisesIds.addAll(reqDto.getCanViewPremisesIds());
                } else {
                    premisesIds.addAll(pId);
                }
            }
            entity.setPremisesIds(premisesIds);
        } else if (reqDto.getCanViewPremisesIds() != null && reqDto.getCanViewPremisesIds().size() != 0) {
            entity.setPremisesIds(reqDto.getCanViewPremisesIds());
        }
    }

    /**
     * 申诉列表
     */
    @Override
    public GetCPAppealPageResDto getCPAppealPage(GetCPAppealPageReqDto reqDto) {
        GetCPAppealPageResDto resDto = new GetCPAppealPageResDto();
        resDto.setResult(ResultEnum.FAIL.getNo());
        try {
            suppleRoleCaseMember(reqDto);
            Page<CustomerPremisesDto> cpPage = null;
            if (reqDto.getLoginType().equals(SystemIdEnum.DEVELOPERS.getCode())) {
                cpPage = appealPagePC(reqDto);
            } else if (reqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode()) || reqDto.getLoginType().equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
                cpPage = appealPageAPP(reqDto);
            }
            resDto.setCpPage(cpPage);
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        } catch (Exception e) {
            log.error("获取申诉记录错误: {}", e);
            resDto.setResultMsg("获取申诉记录错误: " + e.getMessage());
        }
        return resDto;
    }

    private Page<CustomerPremisesDto> appealPageAPP(GetCPAppealPageReqDto reqDto) {

        // 申诉待处理记录,过滤条件如下
        // 1、报备状态: 待确认
        // 2、申述次数: 为1
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        CustomerPremisesDto cusPreDto = new CustomerPremisesDto();

        List<Long> premisesPermission = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
        if(CollectionUtils.isEmpty(premisesPermission)) {
        	cusPreDto.setAuthorityPremisesIds(Arrays.asList(-1L));
        }else {
        	cusPreDto.setAuthorityPremisesIds(premisesPermission);
        }
        
        if(SystemIdEnum.ASSISTANT.getCode().equals(reqDto.getLoginType())) {
        	if(reqDto.getAllPremisesFlag() != null && !reqDto.getAllPremisesFlag()) {
        		if(CollectionUtils.isEmpty(reqDto.getPremisesIds())) {
            		cusPreDto.setPremisesIds(Arrays.asList(-1L));
            	}else {
            		cusPreDto.setPremisesIds(reqDto.getPremisesIds());
            	}
        	}
        }else {
        	cusPreDto.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
        }
        // cusPreDto.setProcessStatus(ProcessStatusEnum.pending.getNo());
        cusPreDto.setCustomerStatus(CustomerStatusEnum.normal.getNo());
        cusPreDto.setComplaintsNumber(1L);
        if (StringUtils.isNotBlank(reqDto.getRoleReportWay())) {
            cusPreDto.setRoleReportWay(reqDto.getRoleReportWay());
        }
        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
        cusPreDto.setAgencyDeptIds(deptPermissionList);
//        if (reqDto.getCanViewPartnerIds() != null && reqDto.getCanViewPartnerIds().size() > 0) {
//            cusPreDto.setCanViewPartnerIds(reqDto.getCanViewPartnerIds());
//        }
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
        List<String> adviserUuids = null;
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            cusPreDto.setAdviserUuids(adviserUuids);
        }        
        cusPreDto.setOrders(" t.appeal_time desc");
        Page<CustomerPremisesDto> appealPage = customerPremisesService.getAppealPageModel(cusPreDto,
                com.yixun.common.page.PageUtil.begin(reqDto.getPageNo(), reqDto.getPageSize()),
                reqDto.getPageSize());
        List<CustomerPremisesDto> appealList = appealPage.getRows();
        
        Map<Long, Premises> completeNodeMap = new HashMap<>();
        if(SystemIdEnum.ASSISTANT.getCode().equals(reqDto.getLoginType())) {
        	 PremisesDto preDto = new PremisesDto();
             preDto.setName(reqDto.getName());
             preDto.setPremisesIds(reqDto.getPremisesIds());
             List<Premises> premisesList = premisesService.selectIdListByDto(preDto);
             completeNodeMap = premisesList.stream()
            		 .collect(Collectors.toMap(Premises::getId, item -> item));
        }
        if (null != appealList && appealList.size() > 0) {
            for (CustomerPremisesDto appeal : appealList) {
                // 将申诉理由赋值给备注
                appeal.setRemark(appeal.getAppealReason());
                // 计算带看保护时间
                Date visitProtectTime = appeal.getVisitProtectTime();
                Calendar calendar = Calendar.getInstance();
                // 默认报备: 非带看保护期中......
                appeal.setVisitProtecting(false);
                if(completeNodeMap.get(appeal.getPremisesId()) != null) {
                	appeal.setPremisesName(completeNodeMap.get(appeal.getPremisesId()).getName());
                }
                // 判断是否特殊报备: 特殊报备记录,皆为非带看保护中记录....
                String reportType = appeal.getReportType();
                if (StringUtils.isEmpty(reportType) || ReportTypeEnum.type_1.getNo().equals(reportType)) {
                    if (null != visitProtectTime) {
                        // 比较带看保护时间是否大于当前时间
                        // 大于当前时间: 带看保护中 小于当前时间: 已过保护时间,可操作记录
                        if (visitProtectTime.compareTo(calendar.getTime()) > 0) {
                            appeal.setVisitProtecting(true);
                        }
                    }
                }

                // 申诉时间
                if (appeal.getAppealTime() != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    appeal.setAppealDate(sdf.format(appeal.getAppealTime()));
                }

                // 判断是否隐藏经纪人电话
                if(Objects.nonNull(reqDto.getHideAgentPhone()) && Boolean.TRUE.equals(reqDto.getHideAgentPhone())){
                	if(StringUtils.isNotBlank(appeal.getMobile())) {
                		appeal.setStaffPhone(ReportWayEnum.convertMobileByReportWay(appeal.getMobile(), ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo()));
                	}
                }
            }
        }
        appealPage.setRows(appealList);
        appealPage.setPageNumber(reqDto.getPageNo());
        int totalPages = (int) Math.ceil(new Double(appealPage.getTotal()) / reqDto.getPageSize().doubleValue());
        appealPage.setTotalPages(totalPages);
        appealPage.setPageSize(reqDto.getPageSize());
        return appealPage;
    }

    private Page<CustomerPremisesDto> appealPagePC(GetCPAppealPageReqDto reqDto)
            throws ParseException {
        CustomerPremisesDto entity = new CustomerPremisesDto();
        Map<String, Integer> map = PageUtil.getPageInfo(reqDto.getPageNo(), reqDto.getPageSize());
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        // 构建当前登录人可查看楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(partnerInfo.getId());
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
        List<String> adviserUuids = null;
        if (StringUtils.isNotBlank(reqDto.getName())) {
        	entity.setName(reqDto.getName());
        }
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            entity.setAdviserUuids(adviserUuids);
        }
        if (CollectionUtils.isNotEmpty(premisesIds)){
            entity.setAuthorityPremisesIds(premisesIds);
        }else {
            entity.setPremisesId(Long.valueOf("-1"));
        }
        if (!StringUtils.isEmpty(reqDto.getAppealTimeBefore())) {
            String before = reqDto.getAppealTimeBefore() + " 00:00:00";
            entity.setAppealTimeBefore(sdf.parse(before));
        }
        if (!StringUtils.isEmpty(reqDto.getAppealTimeAfter())) {
            String after = reqDto.getAppealTimeAfter() + " 23:59:59";
            entity.setAppealTimeAfter(sdf.parse(after));
        }
        // 经纪人
        if (!StringUtils.isEmpty(reqDto.getAgentId())) {
            entity.setStaffId(Long.valueOf(reqDto.getAgentId()));
        }
        // 经纪公司
        if (!StringUtils.isEmpty(reqDto.getCompanyId())) {
            entity.setStaffCompanyId(Long.valueOf(reqDto.getCompanyId()));
        }
        if (StringUtils.isNotBlank(reqDto.getRoleReportWay())) {
            entity.setRoleReportWay(reqDto.getRoleReportWay());
        }
        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
        entity.setAgencyDeptIds(deptPermissionList);
//        if (reqDto.getCanViewPartnerIds() != null && reqDto.getCanViewPartnerIds().size() > 0) {
//            entity.setCanViewPartnerIds(reqDto.getCanViewPartnerIds());
//        }
        entity.setAppealSearch("T");
        entity.setOrders(" t.appeal_time desc");
        Page<CustomerPremises> cpPage = customerPremisesService.getPageModel(entity, map.get("startRow"), map.get("endRow"));
        Page<CustomerPremisesDto> cpDtoPage = new Page<>();
        List<CustomerPremisesDto> cpList = new ArrayList<>();
        for (CustomerPremises customerPremises : cpPage.getRows()) {
            CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
            BeanUtils.copyProperties(customerPremises, customerPremisesDto);
            // 判断是否隐藏经纪人电话
            if(Objects.nonNull(reqDto.getHideAgentPhone()) && Boolean.TRUE.equals(reqDto.getHideAgentPhone())){
                customerPremisesDto.setStaffPhone(ReportWayEnum.convertMobileByReportWay(customerPremises.getStaffPhone(), ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo()));
            }
            cpList.add(customerPremisesDto);
        }
        cpDtoPage.setRows(cpList);
//		cpDtoPage.setPageInfo(cpPage.getTotal(),map.get("startRow"), map.get("endRow")); 诸如此类方法要注意
        cpDtoPage.setPageInfo(cpPage.getTotal(), com.yixun.common.page.PageUtil.begin(reqDto.getPageNo(), reqDto.getPageSize()), reqDto.getPageNo() * reqDto.getPageSize());
        return cpDtoPage;
    }

    @Override
    public Page<AgentRankReport> queryAgentRankReport(AgentRankReportParam agentRankReportParam, int begin, int end) {
        Page<AgentRankReport> page = new Page<>();
        List<AgentRankReport> reportList = customerPremisesMapper.queryAgentRankReportByCompanyId(agentRankReportParam, begin, end);
        int count = customerPremisesMapper.countAgentRankReportByCompanyId(agentRankReportParam);
        page.setRows(reportList);
        page.setPageInfo(count, begin, begin + end);
        return page;
    }

    @Override
    public GetHasCPcusListResDto getHasCPcusList(GetHasCPcusListReqDto getHasCPcusListReqDto) {
        GetHasCPcusListResDto resDto = new GetHasCPcusListResDto();
        CustomerPremisesDto entity = new CustomerPremisesDto();
        // 预留楼盘ID,为查询楼盘信息准备
        Long premisesId = getHasCPcusListReqDto.getPremisesId();
        Long staffId = Long.valueOf(getHasCPcusListReqDto.getUserId());
        PartnerInfo pi = partnerInfoService.selectById(staffId);
        // 清掉楼盘ID,查询登录客户推荐过的客户
        entity.setPremisesId(null);
        entity.setStaffId(staffId);
        entity.setStaffCompanyId(pi.getHigherid());
        entity.setSearchContent(getHasCPcusListReqDto.getSearchContent());
        List<CustomerPremises> cpList = customerPremisesService.findCustomerListByStaffId(entity);
        CustomerListByStaffIdResDto customerResDto = new CustomerListByStaffIdResDto();
        if (null != cpList) {
            List<CustomerListByStaffId> customerList = new ArrayList<>();
            for (CustomerPremises cp : cpList) {
                String mobile = cp.getMobile();
                if (mobile.indexOf(StringConstant.THREE_STAR) >= 0) {
                    continue;
                }
                CustomerListByStaffId customer = new CustomerListByStaffId();
                customer.setName(cp.getName());
                customer.setMobile(cp.getMobile());
                customer.setGender(cp.getGender());
                customer.setEmail(cp.getEmail());
                customerList.add(customer);
            }
            if (customerList.size() > 0) {
                customerResDto.setCustomerList(customerList);
            }
        }

        Premises premises = premisesService.selectSimpleById(premisesId);
        if (null != premises) {
            customerResDto.setPremisesId(String.valueOf(premises.getId()));
            customerResDto.setPremisesName(premises.getName());
            customerResDto.setSpecialTime(premises.getSpecialTime());
            customerResDto.setSpecialTimeType(premises.getSpecialTimeType());
            customerResDto.setProtectTime(premises.getVisitProtect());
            customerResDto.setProtectTimeType(premises.getVisitProtectType());
            if (premises.getVisitProtectSwitch() != null)
                customerResDto.setVisitProtectSwitch(premises.getVisitProtectSwitch());
            customerResDto.setReportProtect(premises.getReportProtect() != null ? premises.getReportProtect().toString() : null);
            customerResDto.setReportProtectType(premises.getReportProtectType() != null ? premises.getReportProtectType().toString() : null);
            customerResDto.setReportWay(premises.getReportWay());
        }
        resDto.setCustomerListByStaffIdResDto(customerResDto);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

    @Override
    public GetPerCPCommissionListResDto getPerCPCommissionList(GetPerCPCommissionListReqDto getPerCPCommissionListReqDto) {
    	GetPerCPCommissionListResDto resDto = new GetPerCPCommissionListResDto();
        CustomerPremisesDto entity = new CustomerPremisesDto();
        entity.setCommissionStatus(getPerCPCommissionListReqDto.getCommissionStatus());
        entity.setStaffId(Long.valueOf(getPerCPCommissionListReqDto.getUserId()));
        PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(getPerCPCommissionListReqDto.getUserId()));
        if ("0".equals(pi.getAccountType())) {
            entity.setStaffId(null);
            entity.setStaffCompanyId(pi.getHigherid());
        }
        entity.setOrders("t.create_time desc");
        Integer pageNo = getPerCPCommissionListReqDto.getPageNo();
        Integer pageSize = getPerCPCommissionListReqDto.getPageSize();
        
        Page<CustomerPremisesDto> pageList =
                customerPremisesService.selectCustomerPremisesListByStaffId(entity, com.yixun.common.page.PageUtil.begin(pageNo, pageSize), 
                		pageSize, getPerCPCommissionListReqDto.getLoginType());
        String commisionFlag = companyRelationService2.searchCommisionFlag(pi.getHigherid());
        if ("0".equals(commisionFlag)) {
            List<CustomerPremisesDto> rows = pageList.getRows();
            for (CustomerPremisesDto cus : rows) {
                cus.setTotalAmount(new BigDecimal(0));
                cus.setHasbalance(new BigDecimal(0));
                cus.setCommissionAmount("0");
                cus.setReward(new BigDecimal(0));
                cus.setAgentPendingCommission(new BigDecimal(0));
                cus.setAgentReceivedCommission(new BigDecimal(0));
            }
            // 由于如果佣金不显示，暂时把控制放在error信息中
            pageList.setErrorMsg("comissionFlag");
        }
        pageList.setPageNumber(pageNo);
        int totalPages = (int) Math.ceil(new Double(pageList.getTotal()) / pageSize.doubleValue());
        pageList.setTotalPages(totalPages);
        resDto.setCustomerPremisesDtoPage(pageList);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

    @Override
    public EditCustomerInfoResDto editCustomerInfo(EditCustomerInfoReqDto reqDto) {
        if (reqDto.getCpId() == 0) {
            throw new TServerException("报备标识不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getName())) {
            throw new TServerException("用户姓名不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getGender())) {
            throw new TServerException("用户性别不能为空！");
        }

        //获取原客户信息
        CustomerPremises customerPremises = customerPremisesMapper.selectById(reqDto.getCpId());
        if (customerPremises == null) {
            throw new TServerException("报备信息不存在！");
        }

        StringBuilder remark = new StringBuilder("【编辑客户】");
        if (!customerPremises.getName().equals(reqDto.getName().trim())) {
            remark.append("将客户姓名改为：" + reqDto.getName() + "，原客户姓名为：" + customerPremises.getName() + "；");
        }
        if (!customerPremises.getGender().equals(reqDto.getGender())) {
            remark.append("将客户性别改为：" + GenderEnum.getDescByNo(reqDto.getGender()) + "，原客户性别为：" + GenderEnum.getDescByNo(customerPremises.getGender()) + "；");
        }
        if (StringUtils.isNotBlank(reqDto.getRemark()) && 
        		StringUtils.isNotBlank(reqDto.getRemark().trim()) && 
        		!reqDto.getRemark().trim().equals(customerPremises.getRemark())) {
            remark.append("将客户意向改为：" + reqDto.getRemark() + "，原客户意向为：" + customerPremises.getRemark() + "；");
        }

        //更新客户信息
        CustomerPremises cp = new CustomerPremises();
        cp.setId(reqDto.getCpId());
        cp.setName(reqDto.getName());
        cp.setGender(reqDto.getGender());
        cp.setRemark(reqDto.getRemark());
        customerPremisesMapper.edit(cp);

        // 修改客户信息
        // 渠道编辑客户信息不再同步更新经纪人客户信息
        // customerApiService.editCP2EditCustomer(reqDto.getCpId());

        //添加修改记录
        FollowUpListDto followDto = new FollowUpListDto();
        followDto.setStaffId(Long.valueOf(reqDto.getUserId()));
        followDto.setCustomerPremisesId(reqDto.getCpId());
        followDto.setOldConfirmStatus(customerPremises.getConfirmStatus());
        followDto.setNewConfirmStatus(customerPremises.getConfirmStatus());
        followDto.setOldCustomerStatus(customerPremises.getCustomerStatus());
        followDto.setNewCustomerStatus(customerPremises.getCustomerStatus());
        followDto.setRemark(remark.toString());
        followDto.setFollowType(FollowTypeEnum.DEVELOPERS.getNo());
        followUpListService.create(followDto);

        EditCustomerInfoResDto resDto = new EditCustomerInfoResDto();
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        return resDto;
    }

    @Override
    public Boolean checkCompletePhone(Premises premises, CustomerPremises customerPremises, String newConfirmStatus) {
        String completeNode = premises.getCompleteNode();
        String customerStatus = customerPremises.getCustomerStatus();
        String confirmStatus = customerPremises.getConfirmStatusName();
        String mobile = customerPremises.getMobile();
        if (mobile.indexOf(StringConstant.THREE_STAR) < 0) {
            // 全号不校验
            return Boolean.TRUE;
        }
        if (CustomerStatusEnum.no_valid.getNo().equals(customerStatus)
                || ConfirmStatusEnum.sign_fail.getNo().equals(confirmStatus)) {
            // 无效报备记录.不做处理
            return Boolean.TRUE;
        }
        if (CompleteNodeEnum.NODE_1.getNo().equals(completeNode)) {
            return Boolean.TRUE;
        } else if (CompleteNodeEnum.NODE_2.getNo().equals(completeNode)) {
            // 报备审核前需补全号码
            // 所有条件下,都需要补全.
            return Boolean.FALSE;
        } else if (CompleteNodeEnum.NODE_3.getNo().equals(completeNode)) {
            // 到访审核前
            // 因审核通过后为未到访,未到访再审核就是已到访.按照规则,需补全后才能进行到访审核
            // 所以此类情况只有在报备还处于待审核时不需要补全,其余情况下要先补全
            if (CustomerStatusEnum.normal.getNo().equals(customerStatus)) {
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        } else if (CompleteNodeEnum.NODE_4.getNo().equals(completeNode)) {
            // 认筹审核前
            // 根据新的交易状态判断
            if (ConfirmStatusEnum.payDeposit.getNo().equals(newConfirmStatus)
                    || ConfirmStatusEnum.subscribe.getNo().equals(newConfirmStatus)
                    || ConfirmStatusEnum.sign.getNo().equals(newConfirmStatus)
            ) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } else if (CompleteNodeEnum.NODE_5.getNo().equals(completeNode)) {
            // 认购审核前
            // 新交易状态为认购、签约时,需要先补全号码
            if (ConfirmStatusEnum.subscribe.getNo().equals(newConfirmStatus)
                    || ConfirmStatusEnum.sign.getNo().equals(newConfirmStatus)
            ) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } else if (CompleteNodeEnum.NODE_6.getNo().equals(completeNode)) {
            // 认购审核前
            // 新交易状态为签约时,需要先补全号码
            if (ConfirmStatusEnum.sign.getNo().equals(newConfirmStatus)) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }
        return Boolean.TRUE;
    }

    @Override
    public Page<CustomerPremisesDto> getWeappCPPage(GetCustomerPremisesPageReqDto reqDto) {
        Page<CustomerPremisesDto> cpDtoPage = new Page<>();
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        if(Objects.nonNull(partnerInfo)){
            reqDto.setAccountType(partnerInfo.getAccountType());
            reqDto.setMerchantId(partnerInfo.getHigherid());
        }

        CustomerPremisesDto entity = new CustomerPremisesDto();
        // 当前登录用户
        entity.setStaffId(Long.parseLong(reqDto.getUserId()));
        if ("0".equals(reqDto.getAccountType())) {
            entity.setStaffId(null);
            entity.setStaffCompanyId(reqDto.getMerchantId());
        }
        if (StringUtils.isNotBlank(reqDto.getSearchContent())) {
            entity.setSearchContent(reqDto.getSearchContent());
        }
        if (StringUtils.isNotBlank(reqDto.getConfirmStatus())) {
            entity.setConfirmStatus(reqDto.getConfirmStatus());
        }
        switch (StringUtils.defaultIfBlank(reqDto.getCustomerStatus(), "")) {
            case "a":
                entity.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                entity.setDisableType(DisableTypeEnum.report_invalid.getNo());
                break;
            case "b":
                entity.setCustomerStatus(CustomerStatusEnum.no_valid.getNo());
                entity.setDisableType(DisableTypeEnum.visit_invalid.getNo());
                break;
            default:
                entity.setCustomerStatus(reqDto.getCustomerStatus());
                break;
        }
        switch (StringUtils.defaultIfBlank(reqDto.getConfirmStatus(), "")) {
            case "A":
                entity.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                entity.setDisableType(DisableTypeEnum.PAYDEPOSIT_FAILD.getNo());
                break;
            case "B":
                entity.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                entity.setDisableType(DisableTypeEnum.SUBSCRIBE_FAILD.getNo());
                break;
            case "C":
                entity.setConfirmStatus(ConfirmStatusEnum.sign_fail.getNo());
                entity.setDisableType(DisableTypeEnum.SIGN_FAILD.getNo());
                break;
            default:
                entity.setConfirmStatus(reqDto.getConfirmStatus());
                break;
        }
        if(StringUtils.isNotBlank(reqDto.getCreateTime())){
            entity.setCreateTimeBefore(TimeSearchCriteriaEnum.getDateByNo(reqDto.getCreateTime()));
        }
        if(StringUtils.isNotBlank(reqDto.getVisitTime())){
            entity.setVisitTimeBefore(TimeSearchCriteriaEnum.getDateByNo(reqDto.getVisitTime()));
        }
        if(StringUtils.isNotBlank(reqDto.getPayDepositTime())){
            entity.setPayDepositTimeBefore(TimeSearchCriteriaEnum.getDateByNo(reqDto.getPayDepositTime()));
        }
        if(StringUtils.isNotBlank(reqDto.getSubscribeTime())){
            entity.setSubscribeTimeBefore(TimeSearchCriteriaEnum.getDateByNo(reqDto.getSubscribeTime()));
        }
        if(StringUtils.isNotBlank(reqDto.getSignTime())){
            entity.setSignTimeBefore(TimeSearchCriteriaEnum.getDateByNo(reqDto.getSignTime()));
        }
        entity.setOrders("t.create_time desc");
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();

        Page<CustomerPremisesDto> pageList =
                customerPremisesService.getCpPageModel(entity, com.yixun.common.page.PageUtil.begin(pageNo, pageSize), pageSize);
        List<CustomerPremisesDto> rows = pageList.getRows();
        cpDtoPage.setRows(rows);
       return cpDtoPage;
    }

}
